import { getStorage } from './storage';

export async function getLLMAddress() {
  return await getStorage('ollamaAddress');
}

export async function sendRequestToLLM(endpoint, data) {
  const address = await getLLMAddress();
  const url = `${address}${endpoint}`;
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return await response.json();
  } catch (error) {
    console.error('Error sending request to LLM:', error);
    throw error;
  }
}

export async function sendGetRequestToLLM(endpoint, params = {}) {
  const address = await getLLMAddress();
  const url = new URL(`${address}${endpoint}`);
  Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));

  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return await response.json();
  } catch (error) {
    console.error('Error sending GET request to LLM:', error);
    throw error;
  }
}
